package com.jwmp.youkeju.web.filter;


import com.jwmp.core.filter.GenericFilter;
import com.jwmp.rbac.domain.Employee;
import com.jwmp.rbac.util.PermissionUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

// 访问授权过滤器
@WebFilter("/*")
public class AuthorizeFilter extends GenericFilter {
    private List<String> unCheckUri = Arrays.asList("/login.jsp","/login","/randomCode","/admin","/logout");

    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        String uri = req.getRequestURI();
        if (!uri.startsWith("/static") && !unCheckUri.contains(uri)) {
            Object obj = req.getSession().getAttribute("EMPLOYEE_IN_SESSION");
            if(obj == null){
                // 无登录
                resp.sendRedirect("/login.jsp");
                return;
            }

            // 无访问权限并且不是管理员
            Employee emp = (Employee)obj;
            if(!PermissionUtil.hasPermission(emp.getId(),uri) && !emp.getAdmin()){
                // 无权限
                req.setAttribute("errorMsg","无权限访问");
                req.getRequestDispatcher("/admin").forward(req,resp);
                return;
            }
        }

        // 静态资源或有登录有权限或管理员
        chain.doFilter(req,resp);
    }
}
